#include "attendancewin.h"
#include "qsqlerror.h"
#include "qsqlquery.h"
#include "ui_attendancewin.h"

#include <QDateTime>

AttendanceWin::AttendanceWin(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::AttendanceWin)
{
    ui->setupUi(this);

    //qRegisterMetaType<cv::Mat>("cv::Mat");
    //qtcpServer当有客户端连接会发送newconnection
    connect(&m_server,&QTcpServer::newConnection,this,&AttendanceWin::accept_client);
    m_server.listen(QHostAddress::Any,9999);//监听，启动服务器
    bsize=0;

    //给模型绑定表格
    qmodel.setTable("employee");

    //创建一个线程
    QThread *thread=new QThread();

    //把QFaceObject对象移动到thread线程中执行
    fobj.moveToThread(thread);

    //启动线程
    thread->start();

    connect(this,&AttendanceWin::query,&fobj,&QfaceObject::face_query);

    //关联QFaceObject对象里面的send_faceid信号
    connect(&fobj,&QfaceObject::send_faceid,this,&AttendanceWin::recv_faceid);
}

AttendanceWin::~AttendanceWin()
{
    delete ui;
}

void AttendanceWin::accept_client()
{
    //获取与客户端通信的套接字
    m_socket=m_server.nextPendingConnection();

    //当客户端有数据到达会发送readyRead信号
    connect(m_socket,&QTcpSocket::readyRead,this,&AttendanceWin::read_data);
}

void AttendanceWin::read_data()
{
    //读取所有的数据
    // QString msg=m_socket->readAll();
    // qDebug()<<msg;

    QDataStream stream(m_socket);//把套接字绑定到数据流
    stream.setVersion(QDataStream::Qt_6_5);

    if(bsize==0)
    {
        if(m_socket->bytesAvailable()<(qint64)sizeof(bsize))
            return;

        //采集数据的长度
        stream>>bsize;
    }

    if(m_socket->bytesAvailable()<bsize)//说明数据还没有发送完成，返回继续等待
        return;

    QByteArray data;
    stream>>data;
    bsize=0;
    if(data.size()==0)//没有读取到数据
    {
        return;
    }
    //显示图片
    QPixmap mmp;
    mmp.loadFromData(data,"jpg");
    mmp=mmp.scaled(ui->pic_lb->size());
    ui->pic_lb->setPixmap(mmp);

    //识别人脸
    cv::Mat faceImage;
    std::vector<uchar> decode;
    decode.resize(data.size());
    memcpy(decode.data(),data.data(),data.size());
    faceImage=cv::imdecode(decode,cv::IMREAD_COLOR);
    //int faceid=fobj.face_query(faceImage);//消耗资源较多
    //qDebug()<<faceid;
    emit query(faceImage);


}

void AttendanceWin::recv_faceid(int64_t faceid)
{
    //从数据库中查询faceid对应的个人信息
    //给模型设置过滤器

    qDebug()<<"识别到的人脸id"<<faceid;
    if(faceid<0)
    {
        QString sdmsg="{\"employeeID\":\"\",\"name\":\"\",\"department\":\"\",\"time\":\"\"}";
        m_socket->write(sdmsg.toUtf8());
        return;
    }

    qmodel.setFilter(QString("faceID=%1").arg(faceid));

    //查询
    qmodel.select();

    //判断是否查询到数据
    if(qmodel.rowCount()==1)
    {
        //工号，姓名，部门，时间
        //{“employeeID":%1,"name":%2,"department":软件,"time":%3}
        QSqlRecord record=qmodel.record(0);
        QString sdmsg=QString("{\"employeeID\":\"%1\",\"name\":\"%2\",\"department\":\"软件\",\"time\":\"%3\"}")
                            .arg(record.value("employeeID").toString())
                            .arg(record.value("name").toString())
                            .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));

        //m_socket->write(sdmsg.toUtf8());//把打包好的数据发送给客户端

        //把数据写入数据库--考勤表
        //QString insertSql=QString("insert into attendance(employeeID) values('%1')").arg(record.value("employeeID").toString());

        QSqlQuery query;
        query.prepare("insert into attendance(employeeID,attendanceTime) values(:employeeID,datetime('now'))");
        query.bindValue(":employeeID",record.value("employeeID").toString());
        if(!query.exec())
        {
            QString sdmsg="{\"employeeID\":\"\",\"name\":\"\",\"department\":\"\",\"time\":\"\"}";
            m_socket->write(sdmsg.toUtf8());
            qDebug()<<query.lastError().text();
            return;
        }
        else{
            m_socket->write(sdmsg.toUtf8());//把打包好的数据发送给客户端
        }
    }
}
